import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import api from '@/api';

// 定义接口类型
interface SentimentDistribution {
  positive: number;
  neutral: number;
  negative: number;
}

interface SentimentTrendItem {
  date: string;
  positive: number;
  negative: number;
  neutral: number;
}

interface KeywordItem {
  word: string;
  weight: number;
}

interface HotSentimentItem {
  id: number;
  title: string;
  platform: string;
  heat_value: number;
  sentiment_type: number;
}

interface PlatformComparisonItem {
  platform: string;
  count: number;
}

interface SentimentTimeItem {
  id: number;
  time: string;
  value: number;
}

interface PriorityTarget {
  id: number;
  name: string;
  type: string;
  image: string;
  count: number;
  sentiment: number;
  firstSeen: string;
  attention: number;
}

interface ExtremeSentiment {
  most_positive: {
    id: number;
    title: string;
    value: number;
  } | null;
  most_negative: {
    id: number;
    title: string;
    value: number;
  } | null;
}

interface SystemStatus {
  crawler: {
    status: boolean;
    response_time: number;
  };
  nlp: {
    status: boolean;
    response_time: number;
  };
  api: {
    status: boolean;
    response_time: number;
  };
}

// 使用组合式API定义store
export const useHomeStore = defineStore('home', () => {
  // 状态定义
  const loading = ref(false);
  const lastUpdate = ref<Date | null>(null);
  const autoRefresh = ref(true);
  const refreshInterval = ref(60000); // 默认1分钟刷新一次
  const timer = ref<number | null>(null);
  
  // 实时数据总览
  const todayTotal = ref(0);
  const realtimeIncrement = ref(0);
  const platformCount = ref(0);
  
  // 情感分布
  const sentimentDistribution = ref<SentimentDistribution>({
    positive: 0,
    neutral: 0,
    negative: 0
  });
  const sentimentTrend = ref<SentimentTrendItem[]>([]);
  
  // 平台筛选状态
  const activePlatforms = ref<Record<string, boolean>>({});
  
  // 热点排名
  const hotKeywords = ref<KeywordItem[]>([]);
  const hotSentiments = ref<HotSentimentItem[]>([]);
  
  // 舆情趋势图表
  const platformComparison = ref<PlatformComparisonItem[]>([]);
  const sentimentTimeDistribution = ref<SentimentTimeItem[]>([]);
  
  // 关键指标
  const alertCount = ref(0);
  const alertIncrement = ref(0);
  const priorityTargets = ref<PriorityTarget[]>([
    {
      id: 1,
      name: '示例监控目标',
      type: '热门话题',
      image: '',
      count: 235,
      sentiment: 1,
      firstSeen: '2023-10-25 08:30',
      attention: 65
    }
  ]);
  const extremeSentiment = ref<ExtremeSentiment>({
    most_positive: null,
    most_negative: null
  });
  
  // 系统状态
  const systemStatus = ref<SystemStatus>({
    crawler: { status: true, response_time: 0 },
    nlp: { status: true, response_time: 0 },
    api: { status: true, response_time: 0 }
  });
  
  // 计算属性
  const formattedLastUpdate = computed(() => {
    if (!lastUpdate.value) return '未更新';
    return lastUpdate.value.toLocaleTimeString();
  });
  
  const hasUnhandledAlert = computed(() => {
    return alertCount.value > 0;
  });
  
  const sentimentPercentage = computed(() => {
    const total = sentimentDistribution.value.positive + 
                 sentimentDistribution.value.neutral + 
                 sentimentDistribution.value.negative;
    
    if (total === 0) return { positive: 0, neutral: 0, negative: 0 };
    
    return {
      positive: Math.round(sentimentDistribution.value.positive / total * 100),
      neutral: Math.round(sentimentDistribution.value.neutral / total * 100),
      negative: Math.round(sentimentDistribution.value.negative / total * 100)
    };
  });
  
  const filteredPlatformComparison = computed(() => {
    // 如果activePlatforms为空对象，返回全部数据
    if (Object.keys(activePlatforms.value).length === 0) {
      return platformComparison.value;
    }
    
    // 否则返回筛选后的数据
    return platformComparison.value.filter(
      item => activePlatforms.value[item.platform] !== false
    );
  });
  
  const filteredHotSentiments = computed(() => {
    // 如果activePlatforms为空对象，返回全部数据
    if (Object.keys(activePlatforms.value).length === 0) {
      return hotSentiments.value;
    }
    
    // 否则返回筛选后的数据
    return hotSentiments.value.filter(
      item => activePlatforms.value[item.platform] !== false
    );
  });
  
  // 方法
  // 获取首页数据
  async function fetchHomeData() {
    loading.value = true;
    
    try {
      console.log('正在请求首页数据...');
      const data = await api.getHomeStats();
      console.log('获取到首页数据:', data);
      
      // 更新状态
      todayTotal.value = data.today_total || 0;
      realtimeIncrement.value = data.realtime_increment || 0;
      platformCount.value = data.platform_count || 0;
      
      if (data.sentiment_distribution) {
        sentimentDistribution.value = data.sentiment_distribution;
      }
      
      // 格式转换：hour -> date
      if (data.sentiment_trend && data.sentiment_trend.length > 0) {
        sentimentTrend.value = data.sentiment_trend.map((item: any) => ({
          date: item.hour,
          positive: item.positive,
          negative: item.negative,
          neutral: item.neutral
        }));
        console.log('转换后的情感趋势数据:', sentimentTrend.value);
      }
      
      if (data.hot_keywords) {
        hotKeywords.value = data.hot_keywords;
        console.log('热门关键词数据:', hotKeywords.value);
      }
      
      if (data.hot_sentiments) {
        hotSentiments.value = data.hot_sentiments;
      }
      
      if (data.platform_comparison) {
        platformComparison.value = data.platform_comparison;
      }
      
      if (data.sentiment_time_distribution) {
        sentimentTimeDistribution.value = data.sentiment_time_distribution;
      }
      
      alertCount.value = data.alert_count || 0;
      alertIncrement.value = data.alert_increment || 0;
      
      // 确保 priorityTargets 有所有必需的字段
      if (data.priority_targets) {
        priorityTargets.value = data.priority_targets.map((target: any) => ({
          id: target.id,
          name: target.name,
          type: target.type,
          image: target.image,
          count: target.count || 0,
          sentiment: target.sentiment || 0,
          firstSeen: target.firstSeen || '未知',
          attention: target.attention || 50
        }));
      }
      
      if (data.extreme_sentiment) {
        extremeSentiment.value = data.extreme_sentiment;
      }
      
      if (data.system_status) {
        systemStatus.value = data.system_status;
      }
      
      // 初始化平台状态（如果为空）
      initActivePlatforms();
      
      lastUpdate.value = new Date();
    } catch (error: any) {
      console.error('获取首页数据失败:', error);
      if (error.response) {
        console.error('错误响应状态:', error.response.status);
        console.error('错误响应数据:', error.response.data);
      }
      // 使用模拟数据进行显示
      useMockData();
    } finally {
      loading.value = false;
    }
  }
  
  // 使用模拟数据
  function useMockData() {
    console.log('使用模拟数据显示...');
    
    // 基本统计数据
    todayTotal.value = 1258;
    realtimeIncrement.value = 23;
    platformCount.value = 8;
    
    // 情感分布
    sentimentDistribution.value = {
      positive: 568,
      neutral: 423,
      negative: 267
    };
    
    // 模拟24小时情感趋势 - 使用更符合真实情况的数据波动
    const mockTrend = [];
    // 基础值，确保每种情感有基本数值
    const basePositive = 8;
    const baseNeutral = 6;
    const baseNegative = 4;
    
    // 波动系数，用于模拟一天中的数据波动
    const fluctuationPositive = [0.7, 0.5, 0.3, 0.2, 0.1, 0.3, 0.5, 0.8, 1.2, 1.5, 1.8, 2.0, 
                               1.9, 1.7, 1.5, 1.6, 1.8, 2.0, 1.8, 1.5, 1.3, 1.1, 0.9, 0.8];
    const fluctuationNeutral = [0.8, 0.6, 0.4, 0.3, 0.2, 0.3, 0.6, 1.0, 1.3, 1.5, 1.4, 1.2, 
                              1.1, 1.3, 1.5, 1.6, 1.4, 1.2, 1.0, 0.9, 0.8, 0.7, 0.8, 0.7];
    const fluctuationNegative = [0.5, 0.4, 0.3, 0.2, 0.1, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0, 0.9, 
                               0.8, 0.9, 1.1, 1.3, 1.5, 1.4, 1.2, 1.0, 0.8, 0.7, 0.6, 0.5];
    
    for (let i = 0; i < 24; i++) {
      // 增加随机波动，但保持一定的规律性
      const randomFactor = 0.2; // 随机因子
      const randomPositive = Math.random() * randomFactor;
      const randomNeutral = Math.random() * randomFactor;
      const randomNegative = Math.random() * randomFactor;
      
      mockTrend.push({
        date: `${i.toString().padStart(2, '0')}:00`,
        positive: Math.round((basePositive * fluctuationPositive[i] + randomPositive) * 10) / 10,
        neutral: Math.round((baseNeutral * fluctuationNeutral[i] + randomNeutral) * 10) / 10,
        negative: Math.round((baseNegative * fluctuationNegative[i] + randomNegative) * 10) / 10
      });
    }
    sentimentTrend.value = mockTrend;
    
    // 模拟热门关键词 - 更丰富的热门话题
    hotKeywords.value = [
      { word: '人工智能', weight: 95 },
      { word: '数据安全', weight: 87 },
      { word: '疫情防控', weight: 82 },
      { word: '数字经济', weight: 78 },
      { word: '远程办公', weight: 76 },
      { word: '元宇宙', weight: 72 },
      { word: '芯片技术', weight: 68 },
      { word: '网络安全', weight: 65 },
      { word: '区块链', weight: 62 },
      { word: '大数据', weight: 58 },
      { word: '云计算', weight: 56 },
      { word: '数字人民币', weight: 54 },
      { word: '5G技术', weight: 52 },
      { word: '智能制造', weight: 48 },
      { word: '电子商务', weight: 45 }
    ];
    
    // 模拟热门舆情 - 更多样化的话题和平台
    hotSentiments.value = [
      { id: 1, title: '最新AI技术突破引发行业热议', platform: '知乎', heat_value: 95, sentiment_type: 1 },
      { id: 2, title: '数据安全事件引发公众担忧', platform: '微博', heat_value: 88, sentiment_type: -1 },
      { id: 3, title: '远程办公新模式提升效率', platform: '今日头条', heat_value: 82, sentiment_type: 1 },
      { id: 4, title: '元宇宙概念引发投资热潮', platform: '抖音', heat_value: 78, sentiment_type: 0 },
      { id: 5, title: '疫情防控新政策实施', platform: '微信', heat_value: 75, sentiment_type: 0 },
      { id: 6, title: '数字人民币试点扩大', platform: '新浪财经', heat_value: 72, sentiment_type: 1 },
      { id: 7, title: '芯片短缺影响产业链', platform: '财经网', heat_value: 70, sentiment_type: -1 },
      { id: 8, title: '互联网监管政策收紧', platform: '网易新闻', heat_value: 68, sentiment_type: -1 }
    ];
    
    // 模拟平台比较数据 - 更真实的分布
    platformComparison.value = [
      { platform: '微博', count: 35 },
      { platform: '抖音', count: 28 },
      { platform: '小红书', count: 22 },
      { platform: '知乎', count: 18 },
      { platform: '微信', count: 42 },
      { platform: '今日头条', count: 25 },
      { platform: 'bilibili', count: 15 },
      { platform: '快手', count: 10 }
    ];
    
    // 模拟情感时间分布数据（散点图）- 更符合规律的分布
    const mockScatterData = [];
    // 生成更符合规律的情感分布
    // 早晨6-9点：较积极
    // 中午11-14点：平稳中性
    // 晚上19-22点：波动较大
    
    // 每小时的情感基准值
    const hourBasedSentiment: Record<number, number> = {
      0: -0.2, 1: -0.3, 2: -0.4, 3: -0.3, 4: -0.1, 5: 0.1,
      6: 0.3, 7: 0.4, 8: 0.5, 9: 0.4, 10: 0.2, 11: 0,
      12: -0.1, 13: 0, 14: 0.1, 15: 0.2, 16: 0.3, 17: 0.4,
      18: 0.3, 19: 0.1, 20: -0.1, 21: -0.2, 22: -0.3, 23: -0.2
    };
    
    // 为每个小时生成多个数据点
    for (let hour = 0; hour < 24; hour++) {
      const pointsPerHour = 5 + Math.floor(Math.random() * 5); // 每小时5-10个点
      for (let i = 0; i < pointsPerHour; i++) {
        const minute = Math.floor(Math.random() * 60);
        const baseSentiment = hourBasedSentiment[hour];
        // 添加随机波动，但保持在合理范围内
        const variance = (Math.random() * 0.6) - 0.3; // -0.3到0.3的随机波动
        const sentimentValue = Math.max(-1, Math.min(1, baseSentiment + variance)).toFixed(2);
        
        mockScatterData.push({
          id: mockScatterData.length + 1,
          time: `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
          value: parseFloat(sentimentValue)
        });
      }
    }
    // 排序以确保时间顺序
    mockScatterData.sort((a, b) => {
      return a.time.localeCompare(b.time);
    });
    sentimentTimeDistribution.value = mockScatterData;
    
    // 其他模拟数据
    alertCount.value = 8;
    alertIncrement.value = 3;
    
    // 模拟监控目标 - 更丰富的信息
    priorityTargets.value = [
      {
        id: 1,
        name: '数字经济发展',
        type: '热门话题',
        image: '',
        count: 125,
        sentiment: 0.68,
        firstSeen: '2023-11-05 08:30',
        attention: 78
      },
      {
        id: 2,
        name: '人工智能伦理',
        type: '争议话题',
        image: '',
        count: 98,
        sentiment: -0.25,
        firstSeen: '2023-11-02 14:15',
        attention: 85
      },
      {
        id: 3,
        name: '数据安全事件',
        type: '热点事件',
        image: '',
        count: 56,
        sentiment: -0.75,
        firstSeen: '2023-11-08 10:20',
        attention: 92
      }
    ];
    
    extremeSentiment.value = {
      most_positive: {
        id: 12,
        title: '科技创新推动经济高质量发展',
        value: 0.92
      },
      most_negative: {
        id: 18,
        title: '数据泄露事件引发广泛担忧',
        value: -0.85
      }
    };
    
    systemStatus.value = {
      crawler: { status: true, response_time: 123 },
      nlp: { status: true, response_time: 245 },
      api: { status: true, response_time: 86 }
    };
    
    // 初始化平台状态
    initActivePlatforms();
    
    lastUpdate.value = new Date();
  }
  
  // 初始化平台活跃状态
  function initActivePlatforms() {
    // 如果已经有状态了，不重新初始化
    if (Object.keys(activePlatforms.value).length > 0) return;
    
    const platforms: Record<string, boolean> = {};
    
    // 为所有平台设置默认活跃状态为true
    platformComparison.value.forEach(item => {
      platforms[item.platform] = true;
    });
    
    activePlatforms.value = platforms;
  }
  
  // 更新平台活跃状态
  function updateActivePlatforms(platforms: Record<string, boolean>) {
    activePlatforms.value = platforms;
  }
  
  // 开始自动刷新
  function startAutoRefresh() {
    stopAutoRefresh(); // 先停止之前的定时器
    
    autoRefresh.value = true;
    timer.value = window.setInterval(() => {
      fetchHomeData();
    }, refreshInterval.value);
  }
  
  // 停止自动刷新
  function stopAutoRefresh() {
    if (timer.value !== null) {
      clearInterval(timer.value);
      timer.value = null;
    }
    autoRefresh.value = false;
  }
  
  // 设置刷新间隔
  function setRefreshInterval(interval: number) {
    refreshInterval.value = interval;
    
    if (autoRefresh.value) {
      startAutoRefresh(); // 重新启动定时器
    }
  }
  
  // 手动刷新数据
  async function refresh() {
    await fetchHomeData();
  }
  
  // 返回所有状态和方法
  return {
    // 状态
    loading,
    lastUpdate,
    autoRefresh,
    refreshInterval,
    timer,
    todayTotal,
    realtimeIncrement,
    platformCount,
    sentimentDistribution,
    sentimentTrend,
    activePlatforms,
    hotKeywords,
    hotSentiments,
    platformComparison,
    sentimentTimeDistribution,
    alertCount,
    alertIncrement,
    priorityTargets,
    extremeSentiment,
    systemStatus,
    
    // 计算属性
    formattedLastUpdate,
    hasUnhandledAlert,
    sentimentPercentage,
    filteredPlatformComparison,
    filteredHotSentiments,
    
    // 方法
    fetchHomeData,
    initActivePlatforms,
    updateActivePlatforms,
    startAutoRefresh,
    stopAutoRefresh,
    setRefreshInterval,
    refresh
  };
}); 